package services;

import java.util.Collection;
import java.util.Date;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.Assert;

import repositories.WorkUpdateRepository;
import domain.Project;
import domain.Registration;
import domain.WorkUpdate;

@Service
@Transactional
public class WorkUpdateService {
	
	//Managed Repository
	@Autowired
	private WorkUpdateRepository workUpdateRepository;
	
	//Supporting Services
	@Autowired
	private UserService userService;
	
	//Constructors
	public WorkUpdateService(){
		super();
	}
	
	//Simple CRUD methods
	
	public WorkUpdate create(Registration registration){
		WorkUpdate result; 
		Date currentMoment;
		
		currentMoment = new Date();
		Assert.notNull(registration);
		Assert.isTrue(registration.getUser().equals(userService.findByPrincipal()));
		
		result = new WorkUpdate();
		result.setUpdateMoment(currentMoment);
		result.setRegistration(registration);
		return result;
	}
	
	public void save(WorkUpdate workUpdate){
		Registration registration;
		Project project;
		
		registration = workUpdate.getRegistration();
		project = registration.getProject();
		
		Assert.notNull(workUpdate);
		Assert.notNull(registration);
		Assert.notNull(project);
		Assert.isTrue(workUpdate.getUpdateMoment().after(registration.getRegistrationMoment()));
		Assert.isTrue(workUpdate.getRegistration().getProject().getStatus().equals("Started"));
		Assert.isTrue(workUpdate.getRegistration().getUser().equals(userService.findByPrincipal()));
		
		
		
		registration.setTotalAmountOfWork(registration.getTotalAmountOfWork() + workUpdate.getAmountOfWork());
		if(project.getTotalAmountOfWork() == null){
			project.setTotalAmountOfWork(0.0);
		}
		project.setTotalAmountOfWork(project.getTotalAmountOfWork() + workUpdate.getAmountOfWork());
		
		workUpdateRepository.save(workUpdate);
		
		
	}
	
	public Collection<WorkUpdate> findAll(){
		Collection<WorkUpdate> result;
		
		result = workUpdateRepository.findAll();
		
		return result;
	}
	
	public WorkUpdate findOne(int workUpdateId){
		WorkUpdate result;
		
		result = workUpdateRepository.findOne(workUpdateId);
		
		return result;
	}
	
	//Other Business methods
	
	public Collection<WorkUpdate> findByRegistrationId( int registrationId){
		Collection<WorkUpdate> result;
		
		result = workUpdateRepository.findByRegistrationId(registrationId);
		
		return result;
	}
	
	public Collection<WorkUpdate> findByProjectId (int projectId){
		Collection<WorkUpdate> result;
		
		result= workUpdateRepository.findByProjectId(projectId);
		
		return result;
	}
}
